package com.humanminoritygame.model;

import java.util.SortedSet;
import java.util.TreeSet;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.OneToMany;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.Sort;
import org.hibernate.annotations.SortType;

@Entity
public class Category extends PersistentEntity implements Comparable<Category>{
  //10 segundos, expresados en milisegundos
  public static final int FASTEST_CATEGORY = 10000;
  private String name;
  @Column(unique=true)
  private int frequency;
  
  @OneToMany(cascade = CascadeType.ALL, mappedBy = "category")
  @Sort(type=SortType.NATURAL)
  @Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
  private SortedSet<Room> rooms = new TreeSet<Room>();

  Category() {
  }
  
  public Category(String name, int frequency){
    this.name = name;
    this.frequency = frequency;
  }

  public String getName() {
    return name;
  }

  public void setName(String name) {
    this.name = name;
  }

  public int getFrequency() {
    return frequency;
  }

  public void setFrequency(int frequency) {
    this.frequency = frequency;
  }
  
  public Room getAvailableRoom(){
    for(Room room : rooms){
      if(room.isAvailableForSubscription()){
        return room;
      }
    }
    Room newRoom = new Room(this);
    this.rooms.add(newRoom);
    return newRoom;
  }

  public Room getAvailableExistingRoom(){
    for(Room room : rooms){
      if(room.isAvailableForSubscription()){
        return room;
      }
    }
    return null;
  }
  
  
  public int compareTo(Category category) {
    return (int)(frequency - category.getFrequency());
  }
}
